﻿using Mirror;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Shows_3D
{
    public class NetworkSystem : GDGeek.Singleton<NetworkSystem>
    {
        [SerializeField]
        private NetworkManager _networkManager;
        [SerializeField]
        private Shows3DNetworkDiscovery _networkDiscovery;

        private readonly Dictionary<long, Shows3DServerResponse> discoveredServers = new Dictionary<long, Shows3DServerResponse>();
        
        public Dictionary<long, Shows3DServerResponse> servers => discoveredServers;
        private Shows3DServerResponse serverResponse_;
        public Shows3DServerResponse serverResponse
        {
            get => serverResponse_;
            set => serverResponse_ = value;
        }
        public void onDiscoveredServer(Shows3DServerResponse info)
        {
            if (!discoveredServers.ContainsKey(info.serverId))
            {
                discoveredServers[info.serverId] = info;
            }
        }

        private void Start()
        {
            _networkDiscovery.OnServerFound.AddListener(onDiscoveredServer);
        }
        public void startHost()
        {
            discoveredServers.Clear();
            _networkManager.StartHost();
            _networkDiscovery.AdvertiseServer();
        }
        
        public void StopHost()
        {
            //_networkDiscovery. BroadcastStopHostRequest();
            discoveredServers.Clear();
            _networkManager.StopHost();
            _networkDiscovery.UnAdvertiseServer();
        }
        public void disConnect()
        {
            _networkManager.StopClient();
        }

        public void connect()
        {
            _networkManager.StartClient(serverResponse_.uri);
            _networkDiscovery.StopDiscovery();
        }

        public void connect(Shows3DServerResponse info)
        {
            _networkManager.StartClient(info.uri);
            _networkDiscovery.StopDiscovery();
        }
        public void discovery()
        {
            Debug.Log("start discovery");
            discoveredServers.Clear();
            _networkDiscovery.StartDiscovery();
            //_ = _networkDiscovery.ClientListenMessageAsync();
        }
        
        public void StopDiscovery()
        {
            Debug.Log("Stop discovery");
            discoveredServers.Clear();
            _networkDiscovery.StopDiscovery();
        }

        
    }
}